package cc.bluemc.modules.weixin.action;

import cc.bluemc.modules.adminUser.entity.AdminUser;
import cc.bluemc.modules.weixin.entity.WxPublicAccountEntity;
import cc.bluemc.modules.weixin.service.WxPublicAccountService;
import cc.bluemc.platform.comm.ActionResultMap;
import cc.bluemc.platform.comm.BaseAction;
import cc.bluemc.platform.comm.DataTablesPagination;
import com.alibaba.fastjson.JSONObject;
import com.gson.bean.AuthorizationInfo;
import com.gson.bean.WeixinAccount;
import com.gson.oauth.Authorize3p;
import com.gson.util.ConfKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @Company 陕西识代运筹信息科技股份有限公司
 * @Discription
 * @Author houfengli
 * @CreateDate 2017/2/21 14:01
 * @Version 1.0
 */
@Controller
@RequestMapping(value="/wx3p")
public class Weixin3p  extends BaseAction {

    private static String auth_url="https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=%s&pre_auth_code=%s&redirect_uri=%s";
    private String  redirect_uri= ConfKit.get("wx3p_redirect_uri");
    WeixinAccount weixinAccount =WeixinAccount.getWeixinAccount();

    @Autowired
    private WxPublicAccountService wxPublicAccountService;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    /**
     * 公众号管理页面
     * @param response
     * @return
     */
    @RequestMapping("manage")
    public String manage(HttpServletResponse response,ModelMap map) {

        return "weixin/wx3p/manageList";
    }
    @RequestMapping("toAuth")
    public String toAuth() throws Exception {
        String redirect_url = getAuth_url();
        return "redirect:"+redirect_url;
    }
    @ResponseBody
    @RequestMapping("ajax/getAuthUrl")
    public String getAuth_url() throws Exception {
        String redirect_url = String.format(auth_url, weixinAccount.getAppId(),  Authorize3p.getPreAuthCode(weixinAccount), redirect_uri);
        return redirect_url;
    }

    @RequestMapping("authCallback")
    public String authCallback(@RequestParam(required = true)String auth_code) throws Exception {
        final AuthorizationInfo info = Authorize3p.queryAuth(weixinAccount, auth_code);

        AdminUser adminUser = getAdminUser();
        WxPublicAccountEntity wxPublicAccountEntity = new WxPublicAccountEntity(info);
        wxPublicAccountEntity.setAdminUserId(adminUser.getId());
        wxPublicAccountService.saveOrUpdate(wxPublicAccountEntity);

        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject authorizerInfo = Authorize3p.getAuthorizerInfo(weixinAccount, info.getAuthorizer_appid());
                    WxPublicAccountEntity info= authorizerInfo.getObject("authorizer_info",WxPublicAccountEntity.class);

                    JSONObject authorizer_info = authorizerInfo.getJSONObject("authorizer_info");
                    JSONObject authorization_info = authorizerInfo.getJSONObject("authorization_info");

                    info.setAppid(authorization_info.getString("authorizer_appid"));
                    info.setAuthorizerTime(new Date());

                    info.setServiceTypeInfo(authorizer_info.getJSONObject("service_type_info").getInteger("id"));
                    info.setVerifyTypeInfo(authorizer_info.getJSONObject("verify_type_info").getInteger("id"));
                    info.setBusinessInfo(authorizer_info.getString("business_info"));

                    wxPublicAccountService.saveOrUpdate(info);
                } catch (Exception e) {
                    log.error("异步保存授权方的公众号帐号基本信息异常",e);
                }
            }
        });

        return "redirect:manage";
    }

    /**
     * 分布查询数据
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping("pageList")
    public DataTablesPagination listPage(DataTablesPagination page,HttpServletRequest request){
        AdminUser adminUser = getAdminUser();
        wxPublicAccountService.getListOfPage(page,adminUser.getId());
        return page;
    }
    /**
     * 删除
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("del")
    public ActionResultMap del(WxPublicAccountEntity wxPublicAccount) throws Exception{
        wxPublicAccountService.delete(wxPublicAccount);
        resultMap.setMsg("删除成功！");
        return resultMap;
    }
}
